<!--
 * @Descripttion: 
 * @version: 
 * @Author: ybac
 * @Date: 2022-08-09 13:44:45
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2022-08-25 15:58:32
-->
<template>
  <div>
    <a-modal v-model="visible" :title="title" @ok="handleOk" @cancel="handleClose" :confirmLoading="confirmLoading">
      <a-form :form="form" @submit="handleOk" layout="horizontal" :labelCol="{ span: 5 }" :wrapperCol="{ span: 18 }">
        <a-form-item label="批次编号">
          <a-input
            v-decorator="[
              'batchCode',
              {
                rules: [
                  {
                    required: true,
                    message: '请输入批次编号或自动生成',
                  },
                  {
                    message: '该值不可用，系统中已存在！',
                    validator: (rule, value, callback) =>
                      validateDuplicateValue('mess_product_batch', 'batch_code', value, queryId, callback),
                  },
                ],
              },
            ]"
            placeholder="请输入"
            :disabled="isEdit"
          />
          <span class="btn-text code-btn" v-if="!isEdit" @click="genEntityCode">自动生成</span>
        </a-form-item>
        <a-form-item label="初始工序" prop="originTaskId">
          <a-select
            placeholder="请选择"
            allowClear
            showSearch
            @change="changeTask"
            v-decorator="['originTaskId', { rules: [{ required: true, message: '请选择初始工序' }] }]"
          >
            <a-select-option v-for="option in processList" :key="option.id" :value="option.id">{{option.showName}}</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="报工单位" prop="processWorkUnitText">
          <a-input disabled v-decorator="['processWorkUnitText']" placeholder="请选择初始工序" />
        </a-form-item>
        <a-form-item label="计划生产数" prop="planProductionNum">
          <a-input
            v-decorator="['planProductionNum', { rules: [{ required: true, message: '请输入' }, { validator: validateToPrice }] }]"
            @input="(e) => inputNum(e)"
            placeholder="请输入"
          />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>
<script>
import { API } from '@/api/requestFzs'
import { messProductBatchAdd, messProductBatchEdit, getTaskOptionList } from '@/api/productOrder'
import { validateDuplicateValue, clearNoNum } from '@/utils/util'
export default {
  data() {
    return {
      visible: false,
      validateDuplicateValue,
      form: this.$form.createForm(this, { name: 'coordinated' }),
      queryId: '', // 用于校验编号唯一性
      processList: [],
      isEdit: false,
      confirmLoading: false,
      orderInfo: {},
      title: '添加批次'
    }
  },
  methods: {
    showModal(val, list) {
      this.form.resetFields()
      this.isEdit = false
      this.orderInfo = val
      this.processList = list
      this.visible = true
    },
    showEditModal(val, list) {
      this.title = '编辑批次'
      this.orderInfo = {orderId: val.orderId, id: val.id}
      this.queryId = val.id
      if (list) {
        this.processList = list
      } else {
        getTaskOptionList({ orderId: val.orderId }).then((res) => {
          this.processList = res.result || []
        })
      }
      this.isEdit = true
      this.visible = true
      this.$nextTick(() => {
        this.form.setFieldsValue(val)
      })
    },
    /* 自动生成 */
    genEntityCode() {
      API.messProductBatchGenCode({ prefix: this.orderInfo.code }).then((res) => {
        if (res.code == 200) {
          this.form.setFieldsValue({
            batchCode: res.result,
          })
        } else {
          this.$antdMessage.error(res.message)
        }
      })
    },
    changeTask(v) {
      if (v) {
        let task = this.processList.find(item => item.id == v)
        this.form.setFieldsValue({
          processWorkUnitText: task.processWorkUnitText,
        })
      } else {
        this.form.setFieldsValue({
          processWorkUnitText: '',
        })
      }
    },
    inputNum(e) {
      this.form.setFieldsValue({
        planProductionNum: clearNoNum(e.target.value),
      })
    },
    /* 数量校验大于0 */
    validateToPrice(rule, value, callback) {
      if (!value) {
        callback()
        return
      }
      if (/[1-9]+[0-9]*/.test(value)) {
        callback()
      } else {
        callback('必须大于0')
      }
    },
    handleOk() {
      let api = messProductBatchAdd
      this.form.validateFields((err, formValues) => {
        console.log(err, formValues)
        if (!err) {
          let params = {...formValues}
          if (this.isEdit) {
            params = {...formValues,...this.orderInfo}
            api = messProductBatchEdit
          }
          this.confirmLoading = true
          api(params).then(res => {
            if (res.success) {
              this.$antdMessage.success(res.message)
              this.$emit('refresh')
              this.handleClose()
            } else {
              this.$antdMessage.error(res.message)
            }
            this.confirmLoading = false
          })
        }
      })
    },
    handleClose() {
      this.form.resetFields()
      this.visible = false
    },
  },
}
</script>

<style lang="less" scoped>
.code-btn {
  position: absolute;
  right: 10px;
  top: -13px;
}
</style>
